/*Author: Rony Lahav (ID:043489889)*/

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


/**
 * This class initializes the peer's UDP DatagramSocket to listen to incoming UDP messages.
 * When one is received the message process session is activated
 */
public class UDPListener implements Runnable {
	int myPort = final_project.getMyUDPPort();
	public DatagramSocket listenerDS=null;
	
	public UDPListener(DatagramSocket soc){
		listenerDS=soc;
	}
	
	public void run()
	{		
		do {
			try	
			{
				if (!final_project.isShutDown()){
					listenerDS.setSoTimeout(1000);
					// Preparing the buffer for receiving a message
					byte[] buffer = new byte[final_project.maxBufferSize];
					DatagramPacket rcvPacket = new DatagramPacket(buffer, buffer.length);
					listenerDS.receive(rcvPacket);
					//Get sender details and message and start the processing thread
					int senderPort = rcvPacket.getPort();
					String senderIP = rcvPacket.getAddress().getHostAddress();
					String msg =  new String(rcvPacket.getData(),0,rcvPacket.getLength());
					UDPListenerProcessMessage udpProcMsg = null;
					if (final_project.amIanSN)
						udpProcMsg = new UDPListenerProcessMessageSN(senderIP,senderPort,msg);
					else
						udpProcMsg = new UDPListenerProcessMessage(senderIP,senderPort,msg);
					Thread thread = new Thread(udpProcMsg);
					final_project.addThreadToLivingList(final_project.getNewUniqueID(), thread);
					thread.start();
				}
			}
			catch(SocketTimeoutException e1){}
			catch(IOException e2){}
		} while (!final_project.isShutDown()); // while not shut down
		
		try{
			if (listenerDS != null && !listenerDS.isClosed()){
				listenerDS.close();
			}
		}catch(Exception e){}
	}
}
